#!/usr/bin/env bash
set -euo pipefail

# Usage: scripts/run_local_bdt.sh [N=4] [DURATION=30]

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"

N="${1:-4}"
DURATION="${2:-30}"

echo "[run_local_bdt] root: $ROOT_DIR, N=$N, duration=${DURATION}s"

# Output data root and timestamped run dir
DATA_ROOT="$ROOT_DIR/data"
TS=$(date +%Y%m%d_%H%M%S)
RUN_DIR="$DATA_ROOT/$TS"
export RUN_DIR
mkdir -p "$RUN_DIR/logs"
mkdir -p "$RUN_DIR/results"
echo "[run_local_bdt] data dir: $RUN_DIR"

# Build Go binary
echo "[run_local_bdt] building Go binary..."
go mod tidy
go build -o bdt .

# Generate configurations for local testing
echo "[run_local_bdt] generating configurations..."
python3 - <<'PY'
import yaml
import os

N = int(os.environ.get('N_VAL','4'))
RUN_DIR = os.environ['RUN_DIR']

# Create config template for local testing
config_template = {
    'id_name': {i: f'node{i}' for i in range(N)},
    'id_ip': {i: f'127.0.0.1' for i in range(N)},
    'id_p2p_port': {i: 9000 + i for i in range(N)},  # Different ports for each node
    'log_level': 1,
    'max_pool': 10,
    'timeout': 1000,
    'mock_latency': 10,
    'ddos': True,
    'max_payload_size': 500,
    'tx_size': 512,
    'wait_time': 5  # Reduced wait time for local testing
}

# Write config template
template_path = os.path.join(RUN_DIR, 'config_temp.yaml')
with open(template_path, 'w') as f:
    yaml.dump(config_template, f, default_flow_style=False)

print(f'Config template written to: {template_path}')
PY
export N_VAL="$N"

# Generate individual node configurations
echo "[run_local_bdt] generating node configurations..."
cd config_gen
cp "$RUN_DIR/config_temp.yaml" ./config_temp.yaml
go run main.go

# Fix case sensitivity issues in generated configs
for yaml_file in *.yaml; do
  if [ -f "$yaml_file" ]; then
    # Convert TSPubKey to tspubkey and TSShare to tsshare
    sed -i 's/TSPubKey:/tspubkey:/g; s/TSShare:/tsshare:/g' "$yaml_file"
  fi
done

cp *.yaml "$RUN_DIR/"
cd ..

echo "[run_local_bdt] configurations generated"

# Cleanup old processes
tmux kill-server || true

# Start BDT nodes
echo "[run_local_bdt] starting $N BDT node(s)..."
for (( i=0; i< N; i++ )); do
  session="bdt_$i"
  config_file="$RUN_DIR/node$i.yaml"
  # Change to the directory containing the config file and run bdt
  cmd="cd $RUN_DIR && $ROOT_DIR/bdt -config node$i"
  tmux new -d -s "$session" "$cmd > $RUN_DIR/logs/node-$i.log 2>&1"
  echo "[run_local_bdt] started node $i with config: $config_file"
done

echo "[run_local_bdt] running for ${DURATION}s..."
sleep "$DURATION"

echo "[run_local_bdt] stopping tmux server..."
tmux kill-server || true

echo "[run_local_bdt] logs:"
ls -la "$RUN_DIR/logs" || true

# Parse logs for simple statistics
echo "[run_local_bdt] parsing logs for statistics..."
python3 - <<'PY'
import glob, json, os
from pathlib import Path

RUN_DIR = os.environ['RUN_DIR']
logs = sorted(glob.glob(os.path.join(RUN_DIR,'logs/*.log')))
if not logs:
    print('no logs found, skip stats')
else:
    def parse_log(path: str) -> dict:
        result = {'file': Path(path).name, 'lines': 0, 'proposals': 0, 'commits': 0, 'errors': 0}
        try:
            with open(path, 'r', errors='ignore') as f:
                for line in f:
                    result['lines'] += 1
                    if 'proposal' in line.lower():
                        result['proposals'] += 1
                    if 'commit' in line.lower():
                        result['commits'] += 1
                    if 'error' in line.lower() or 'panic' in line.lower():
                        result['errors'] += 1
        except Exception as e:
            result['parse_error'] = str(e)
        return result

    per_file = {Path(p).stem: parse_log(p) for p in logs}
    total_proposals = sum(r.get('proposals', 0) for r in per_file.values())
    total_commits = sum(r.get('commits', 0) for r in per_file.values())
    total_errors = sum(r.get('errors', 0) for r in per_file.values())

    # duration from env
    try:
        duration = int(os.environ.get('DURATION_VAL','0'))
        if duration <= 0:
            duration = 1
    except Exception:
        duration = 1

    print('--- STATS ---')
    print('per_file_results:', per_file)
    print('total_proposals:', total_proposals)
    print('total_commits:', total_commits)
    print('total_errors:', total_errors)
    print('duration_s:', duration)
    print('---------------')
    
    # Write results to CSV
    import csv
    N = int(os.environ.get('N_VAL','4'))
    result_file = os.path.join(RUN_DIR, 'results/result.csv')
    with open(result_file, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['timestamp', 'N', 'duration_s', 'total_proposals', 'total_commits', 'total_errors', 'per_file_results'])
        writer.writerow([os.environ.get('TS',''), N, duration, total_proposals, total_commits, total_errors, str(per_file)])
    print(f'results written to: {result_file}')
PY
export N_VAL="$N"
export DURATION_VAL="$DURATION"
export TS

echo "[run_local_bdt] done."
